import { customRef } from "vue";

// debounce
export function useDebounceRef<T>(initialValue: T, delay: number) {
  let value = initialValue;
  let timeout: number;

  // 返回一个自定义 ref 对象
  return customRef(
    (track, trigger): { get: () => T; set: (newValue: T) => void } => {
      return {
        get() {
          track(); // 追踪变化
          return value;
        },
        set(newValue: T) {
          value = newValue;
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            trigger(); // 触发更新
          }, delay);
        },
      };
    },
  );
}
